package com.stp.spi;

import java.util.ArrayList;
import java.util.List;
import java.util.ServiceLoader;

/**
 * 加载具体的服务实现
 */
public class LandingOnTheMoonLoader {
    private static volatile LandingOnTheMoonLoader LOADER;

    private final LandingOnTheMoon landingOnTheMoon;

    private final List<LandingOnTheMoon> landingOnTheMoons;

    /**
     * 加载服务
     * */
    private LandingOnTheMoonLoader() {
        ServiceLoader<LandingOnTheMoon> loader = ServiceLoader.load(LandingOnTheMoon.class);
        List<LandingOnTheMoon> list = new ArrayList<>();
        for (LandingOnTheMoon landingOnTheMoon : loader) {
            list.add(landingOnTheMoon);
        }
        landingOnTheMoons = list;
        if (!list.isEmpty()) {
            // 取第一个
            landingOnTheMoon = list.get(0);
        } else {
            landingOnTheMoon = null;
        }
    }


    /**
     * LandingOnTheMoonLoader 单例加载
     * */
    public static LandingOnTheMoonLoader getLOADER() {
        if (LOADER == null) {
            synchronized (LandingOnTheMoonLoader.class) {
                if (LOADER == null) {
                    LOADER = new LandingOnTheMoonLoader();
                }
            }
        }
        return LOADER;
    }


    public void land(){
        if(landingOnTheMoons.isEmpty()){
            System.out.println("LandingOnTheMoon服务未加载！");
        }else {
            LandingOnTheMoon landingOnTheMoon = landingOnTheMoons.get(0);
            landingOnTheMoon.land();
        }
    }
}
